import common
import DCOracle2
import time
import unittest

from DCOracle2.dco2 import OracleDate

class test_datetime(common.TestCase):

    tables_to_drop = ('datetest',)

    def test_DateConversion(self):

        currentdatetime = time.time()
        
        DCOracle2.registerDateConversion(lambda x: ".date(%s)." % x)
        try:
            c = self.c

            c.execute("create table datetest (id integer, stamp date)")

            now = DCOracle2.DateFromTicks(currentdatetime)

            c.execute("insert into datetest(id, stamp) values(:1, :2)", 1, now)

            self.db.commit()

            c.execute("select * from datetest where id=1")

            r = c.fetchone()

            saved = r[1]

            stime = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(currentdatetime))
            self.assertEqual(str(now),stime)
            self.assertEqual(saved,'.date('+stime+').')
        finally:
            DCOracle2.registerDateConversion(None)

    def test_DateInsertion(self):

        c = self.c

        c.execute('create table datetest (name varchar2(64), when date)')

        day = 60 * 60 * 24
        now = time.time()
        tomorrow = now+1*day
        yesterday = now-1*day
        rsn = now+14*day
        data = (
                ("Now", DCOracle2.DateFromTicks(now)),
                    ("Tomorrow", DCOracle2.DateFromTicks(tomorrow)),
                    ("Yesterday", DCOracle2.DateFromTicks(yesterday)),
                    ("RSN", DCOracle2.DateFromTicks(rsn))
                )

        c.executemany('insert into datetest (name, when) values (:1, :2)', data)

        self.db.commit()

        c.execute('select * from datetest')

        self.assertEqual(
            c.fetchall(),
            [
            ['Now', OracleDate(*time.localtime(now)[:6])],
            ['Tomorrow', OracleDate(*time.localtime(tomorrow)[:6])],
            ['Yesterday', OracleDate(*time.localtime(yesterday)[:6])],
            ['RSN', OracleDate(*time.localtime(rsn)[:6])]
            ]
            )

if __name__ == '__main__':
    unittest.main()        
